package cn.itcast.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.itcast.constant.MessageConstant;
import cn.itcast.constant.RedisConstant;
import cn.itcast.entity.Result;
import cn.itcast.utils.SMSUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping(path = "/sms")
public class SmsController {

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    /**
     * 发送短信验证码
     *
     * @param phone
     * @return
     */
    @PostMapping(path = "/sendCode")
    public Result sendCode(String phone) {
        try {
            //生成6位随机数字验证码
//            String numeric = RandomStringUtils.randomNumeric(6);
            String numeric = "123456";

           if (!ObjectUtil.isEmpty(redisTemplate.opsForValue().get(RedisConstant.SENDTYPE_LOGIN + phone))){
                return new Result(false,MessageConstant.NOTVERDUE);
            }
            // 将验证码存储到redis中,设置五分钟过期
            redisTemplate.opsForValue().set(RedisConstant.SENDTYPE_LOGIN + phone, numeric,5,TimeUnit.MINUTES);


            //调用工具类发送验证码
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, phone, numeric);

            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (Exception exception) {
            exception.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }

    /**
     * 发送短信验证码
     *
     * @param phone
     * @return
     */
    @PostMapping(path = "/sendLoginCode")
    public Result sendLoginCode(String phone) {
        try {
            //生成6位随机数字验证码
//            String numeric = RandomStringUtils.randomNumeric(6);
            String numeric = "123456";

            // 判断redis中是否有验证码
            if (!ObjectUtil.isEmpty(redisTemplate.opsForValue().get(RedisConstant.SENDTYPE_LOGIN + phone))){
                return new Result(false,MessageConstant.NOTVERDUE);
            }
            // 将验证码存储到redis中,设置五分钟过期
            redisTemplate.opsForValue().set(RedisConstant.SENDTYPE_LOGIN + phone, numeric,5,TimeUnit.MINUTES);


            //调用工具类发送验证码
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, phone, numeric);

            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (Exception exception) {
            exception.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }
}
